#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <cstdlib>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
namespace yui
{
    class UdpClient
    {
        public:
        UdpClient(const std::string&ip,uint16_t port)
            :server_ip_(ip),server_port_(port)
        {}
        ~UdpClient()
        {}
        //初始化客户端
        void InitClient()
        {
            sock_ = socket(AF_INET,SOCK_DGRAM,0);
            if(sock_==-1)
            {
                perror("socket fail");
                exit(1);
            }
            std::cout<<"socket创建成功:"<<sock_<<std::endl;
            bzero(&svr_,sizeof(svr_));
            svr_.sin_family = AF_INET;
            svr_.sin_addr.s_addr = inet_addr(server_ip_.c_str());
            svr_.sin_port = htons(server_port_);
        }
        //启动个客户端
        void StartClient()
        {
            char buff[4096];
            while(true)
            {
                std::string msg;
                std::cout<<"输入消息#";
                std::getline(std::cin,msg);

                ssize_t n = sendto(sock_,msg.c_str(),msg.size(),0,(const struct sockaddr*)&svr_,sizeof(svr_));
                if(n == -1)
                {
                    perror("sendto file");
                    continue;
                }
                // socklen_t len = sizeof(svr_);
                // n = recvfrom(sock_,buff,sizeof(buff)-1,0,(struct sockaddr*)&svr_,&len);
                // if(n>0)
                // {
                //     buff[n] = '\0';
                // }
                // else{
                //     continue;
                // }
                // std::string ip = inet_ntoa(svr_.sin_addr);
                // uint16_t port = ntohs(svr_.sin_port);
                // printf("服务端发来消息[%s:%d]#%s\n",ip.c_str(),port,buff);



            }
        }
        private:
            std::string server_ip_;
            uint16_t server_port_;
            int sock_;
            struct sockaddr_in svr_;

    };
}